'use strict';

const axios = require('axios');
const settings = require('./settings')

// test
// let flag1 = 0;

/**
 * 请求验证码获取cookie
 */
function preLogin() {
    const imgUrl = 'https://reported.17wanxiao.com/captcha.jpg?t=' + Date.now();
    let captchaCookie = '';
    return axios.get(imgUrl, {
        responseType: 'stream',
        timeout: 10000
    }).then(response => {
        // const img = encodeURIComponent(Buffer.from(response.data).toString('base64'));
        for (let c of response.headers['set-cookie']) {
            captchaCookie += c.substring(0, c.indexOf('Path='));
        }
        console.log('请求验证码后响应的cookie:', captchaCookie);
        return captchaCookie;
    });
}

/**
 * 登录
 */
function login(captchaCookie) {
    console.log('***************** 登录请求 *****************');
    const target = 'https://reported.17wanxiao.com/admin/login';
    let loginCookie = '';
    const requestLogin = function () {
        return axios.post(target, {}, {
            params: {
                'username': settings.adminName,
                'securitycode': settings.password,
                'captcha': ''
            },
            headers: {
                'Cookie': captchaCookie,
            },
            timeout: 10000
        }).then(response => {
            // console.log('状态码:', JSON.stringify(response.statusCode));
            // console.log('响应头:\n', JSON.stringify(response.headers, null, '  '));
            console.log('响应数据:\n', JSON.stringify(response.data, null, '  '));
            for (let c of response.headers["set-cookie"]) {
                loginCookie += c.substring(0, c.indexOf('Path='));
            }
            loginCookie = loginCookie.substring(loginCookie.indexOf(';') + 1);
            loginCookie += captchaCookie.substring(0, captchaCookie.indexOf(';') + 1);
            return loginCookie;
        })
    };
    return requestLogin();
}

/**
 * 检查是否打卡
 */
function checkClockIn(loginCookie) {
    const promiseList = [];
    settings.users.forEach(user => {
        const promise = new Promise((resolve, reject) => {
            const check = function () {
                checkUndoneList(loginCookie, user)
                    .then(sendMsg)
                    .then(finished => {
                        if (!finished) {
                            setTimeout(check, settings.interval * 1000);
                        } else {
                            resolve(user.name + ': 已提醒');
                        }
                    })
                    .catch(error => {
                        sendErrMsg(user.name, user.sendKey);
                        reject(error);
                    })
            };
            check();
        }).then(msg => {
            return msg;
        });
        promiseList.push(promise);
    });
    return Promise.all(promiseList);
}

/**
 * 检查未打卡学生列表
 */
function checkUndoneList(cookie, checkedUser) {
    console.log('***************** 查询请求 *****************');
    const target = 'https://reported.17wanxiao.com/student/list2';
    console.log('请求携带的cookie:', cookie);
    return axios.get(target, {
        params: {
            'undo': 0,
            'reportTime': localDate(),
            '_search': false,
            'limit': 100,
            // 'page': 1,
            // 'sidx': 'stuNo',
            // 'order': 'asc',
            // 'stuNo': '',
            // 'grade': '',
            // 'name': '',
        },
        headers: {
            'cookie': cookie
        },
        timeout: 10000
    }).then(response => {
        // 获取学号和姓名
        const studentList = response.data.page.records.map(x => ({
            sno: x.stuNo,
            name: x.name
        }))
        console.log('未打卡学生:', studentList);
        let finished = studentList.findIndex(stu => stu.sno === checkedUser.sno) === -1;

        // test
        // if (checkedUser === settings.users[0]) {
        //     if (++flag1 <= 5) {
        //         finished = false;
        //     }
        // }

        return {'name': checkedUser.name, 'finished': finished, 'sendKey': checkedUser.sendKey};
    });
}

/**
 * 推送打卡是否完成的消息
 */
function sendMsg(msg) {
    const finished = msg.finished;
    if (finished && settings.onlyUnfinished) {
        return finished;
    }
    console.log('************ 推送消息 to ' + msg.name + ' ************');
    const text = finished ? '今日已完成健康打卡！' : '今天还没打卡哦！';
    console.log(text);
    if (settings.sendMsg) {
        const target = 'https://sctapi.ftqq.com/' + msg.sendKey;
        return axios.post(target, {}, {
            params: {
                title: text
            },
            timeout: 10000
        }).then(response => {
            console.log(response.data);
            return finished;
        });
    }
    return finished;
}

/**
 * 推送执行失败的消息
 */
function sendErrMsg(name, sendKey) {
    console.log('************ 推送 error 消息 to ' + name + ' ************');
    if (settings.sendMsg) {
        const target = 'https://sctapi.ftqq.com/' + sendKey;
        axios.post(target, {}, {
            params: {
                title: '服务器出问题啦，记得打卡哦！'
            },
            timeout: 10000
        }).then(response => {
            console.log(response.data);
        });
    }
}

/**
 * 获取东八区日期
 */
function localDate() {
    const s = new Date(Date.now() + 8 * 60 * 60 * 1000).toISOString();
    return s.substring(0, s.indexOf('T'));
}

// 云函数执行入口
exports.handler = (_event, _context, callback) => {
    console.log('start......................');
    preLogin()
        .then(login)
        .then(checkClockIn)
        .then(msg => {
            // test
            // flag1 = 0;
            callback(null, msg);
        })
        .catch(error => {
            callback(error, null);
        });
}

// 本地测试（部署到云函数时注释掉）
console.log('start......................');
preLogin()
    .then(login)
    .then(checkClockIn)
    .then(msg => {
        console.log();
        console.log(msg);
    })
    .catch(error => {
        console.log(error);
    });